package com.ms.p2p.plugin.validation;


import com.ms.common.utils.WebErrors;
import com.ms.p2p.plugin.AutoRegisterPlugin;
import com.ms.p2p.plugin.validation.annotation.SpecialRegexFieldValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.regex.Pattern;

public class SpecialRegexFieldValidate extends AutoRegisterPlugin implements IValidate {

	@Override
	public WebErrors validate(HttpServletRequest request, WebErrors errors,
							  Validations validations, Map<String, String> decodedUriVariables) {
		SpecialRegexFieldValidator[] rfvs = validations.specials();
		for(SpecialRegexFieldValidator rfv : rfvs){
			String fieldName = rfv.fieldName();
			String regex = null;
			switch(rfv.fieldType()){
				case mobile :
					regex = "^(13\\d|145|147|15[0-3]|15[5-9]|177|18[0-3]|18[5-9])\\d{8}$";
					break;
				case telephone :
					regex = "^(0\\d{2,3}-)?([2-9]\\d{6,7})+(-\\d{1,4})?$";
					break;
				case email :
					regex = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$";
					break;
				case idcard :
					regex = "^(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X))|([1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3})$";
					break;
				case postCode :
					regex = "^[1-9]\\d{5}";
					break;
				case mobileOrTelephone :
					regex = "^((13\\d|145|147|15[0-3]|15[5-9]|177|18[0-3]|18[5-9])\\d{8})|((0\\d{2,3}-)?([2-9]\\d{6,7})+(-\\d{1,4})?)$";
					break;
			}
			String value = request.getParameter(fieldName);
			if(StringUtils.isEmpty(value) && decodedUriVariables != null){
				value = decodedUriVariables.get(fieldName);
			}
			if(rfv.isNullable() && StringUtils.isBlank(value)){
				continue;
			}
			if(StringUtils.isBlank(value)
					|| !Pattern.matches(regex, value)){
				if(StringUtils.isNotBlank(rfv.message())){
					errors.addErrorString(rfv.message());
				}else{
					errors.addErrorCode("regex.error.special." + rfv.fieldType().name());
				}
			}
		}
		return errors;
	}

	@Override
	public String getType() {
		return "vallidate";
	}

	@Override
	public String getId() {
		return "specialRegexValidate";
	}

	@Override
	public String getName() {
		return "特殊正则校验";
	}

	@Override
	public String getVersion() {
		return "1.0.0";
	}

	@Override
	public String getAuthor() {
		return "fangchen";
	}

	@Override
	public void perform(Object... params) {
		
	}

	@Override
	public void register() {
		
	}

}
